﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Web;
using blackhouse.BlackApart.Business;
using blackhouse.JavaScript.JQuery;
using blackhouse.BlackApart.Business.Apartments;

namespace blackhouse.Aparts.Web.Modules {
	public partial class SortPanel : System.Web.UI.UserControl {

		#region Fields

		private WebApartmentSortModel sortModel;

		#endregion

		#region Event Handlers

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			this.rptSorting.ItemDataBound += new RepeaterItemEventHandler(rptSorting_ItemDataBound);
			this.sortModel = Factory.Instance().GetSorting() as WebApartmentSortModel;
			this.ReceivePostback();
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.AddJavascript();
			this.sortModel.PopulateRepeater(this.rptSorting);
		}

		void rptSorting_ItemDataBound(object sender, RepeaterItemEventArgs e) {
			switch (e.Item.ItemType) {
				case ListItemType.AlternatingItem:
				case ListItemType.Item:
					this.sortModel.RepeaterCommand(e.Item.DataItem, e.Item.FindControl("lnkNav") as WebControl);
					break;

			}
		}

		#endregion

		#region Methods

		public IEnumerable<IApartmentGroup> Sort(IEnumerable<IApartmentGroup> groups) {
			return this.sortModel.Sort(groups);
		}

		private void ReceivePostback() {
			if (!string.IsNullOrEmpty(Request.Form["sort"])) {
				string[] sortParts = Request.Form["sort"].Split(' ');
				if (sortParts.Length == 2) {
					string sortby = sortParts[0];
					WebApartmentSortModel.SortDirection direction;
					if (Enum.TryParse<WebApartmentSortModel.SortDirection>(sortParts[1], true, out direction)) {
						this.sortModel.SortBy = sortby;
						this.sortModel.Direction = direction;
						Response.Redirect(Request.RawUrl);
					}
				}
			}
		}

		public void AddSorter(string key, string name, ApartmentSortModel.SortApartment sorter, ApartmentSortModel.SortDirection direction) {
			this.sortModel.AddSorter(key, name, sorter, direction);
		}

		private void AddJavascript() {
			JQueryLibraries jql = new JQueryLibraries();
			jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.sortPanel.js,blackhouse.Aparts.Web");
		}

		#endregion

	}
}